package com.aabte.spring.validator;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/25
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 处理自定义异常
   */
  @ExceptionHandler(BizException.class)
  public RspDTO handleRRException(BizException e) {
    log.error(e.getMessage(), e);
    return new RspDTO(e.getCode(), e.getMessage());
  }

  /**
   * 方法参数校验
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public RspDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    log.error(e.getMessage(), e);
    return new RspDTO(Constant.PARAM_FAIL_CODE,
        e.getBindingResult().getFieldError().getDefaultMessage());
  }

  /**
   * ValidationException
   */
  @ExceptionHandler(ValidationException.class)
  public RspDTO handleValidationException(ValidationException e) {
    log.error(e.getMessage(), e);
    return new RspDTO(Constant.VALIDATION_CODE, e.getCause().getMessage());
  }

  /**
   * ConstraintViolationException
   */
  @ExceptionHandler(ConstraintViolationException.class)
  public RspDTO handleConstraintViolationException(ConstraintViolationException e) {
    log.error(e.getMessage(), e);
    return new RspDTO(Constant.PARAM_FAIL_CODE, e.getMessage());
  }

  @ExceptionHandler(NoHandlerFoundException.class)
  public RspDTO handlerNoFoundException(Exception e) {
    log.error(e.getMessage(), e);
    return new RspDTO(Constant.NOT_FOUND, "路径不存在，请检查路径是否正确");
  }

  @ExceptionHandler(Exception.class)
  public RspDTO handleException(Exception e) {
    log.error(e.getMessage(), e);
    return new RspDTO(Constant.INNER_ERROR, "系统繁忙,请稍后再试");
  }
}
